package com.cskaoyan.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler  implements TypeHandler<Integer[]> {

    ObjectMapper objectMapper = new ObjectMapper();

    //输入映射
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, Integer[] input, JdbcType jdbcType) throws SQLException {
        //使用json做转换
        String inputString = objectMapper.writeValueAsString(input);
        preparedStatement.setString(index,inputString);
    }

    //输出映射过程：获得查询结果
    @Override
    public Integer[] getResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        return transfer(result);
    }


    @SneakyThrows
    private Integer[] transfer(String result) {
        if(StringUtils.isEmpty(result)){
            return new Integer[0];
        }
        Integer[] integers = objectMapper.readValue(result, Integer[].class);
        return integers;
    }
}
